package com.koc.robot;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLES11;

//Image Quad
public class Quad {
	private Texture mTexture;
	
	//quad in texture
	private int mX;
	private int mY;
	private int mWidth;
	private int mHeight;
	
	//render buffer
	private FloatBuffer mVertexBuffer;
	private FloatBuffer mTextureBuffer;
	
	static int VERTEXES = 4;
	
	public Quad(Texture tex, int x, int y, int width, int height)
	{
		mTexture = tex;
		mX = x;
		mY = y;
		mWidth = width;
		mHeight = height;
		
        ByteBuffer vbb = ByteBuffer.allocateDirect(VERTEXES * 3 * 4);
        vbb.order(ByteOrder.nativeOrder());
        mVertexBuffer = vbb.asFloatBuffer();

        ByteBuffer tbb = ByteBuffer.allocateDirect(VERTEXES * 2 * 4);
        tbb.order(ByteOrder.nativeOrder());
        mTextureBuffer = tbb.asFloatBuffer();
	}
	
	public void render(int x, int y, int width, int height)
	{
		//no image
		if(mTexture.getTextureID() < 0)
			return;
		
		GLES11.glEnableClientState(GLES11.GL_VERTEX_ARRAY);
		GLES11.glEnableClientState(GLES11.GL_TEXTURE_COORD_ARRAY);
		
		GLES11.glBlendFunc(GLES11.GL_SRC_ALPHA, GLES11.GL_ONE_MINUS_SRC_ALPHA);
		
		makeBuffer(x, y, width, height);
		GLES11.glBindTexture(GLES11.GL_TEXTURE_2D, mTexture.getTextureID());
		
		GLES11.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
		GLES11.glEnable(GL10.GL_TEXTURE_2D);
		GLES11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
		GLES11.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, VERTEXES);
	} 
	
	private void makeBuffer(int x, int y, int width, int height)
	{
        float[] coords = {
                // X, Y, Z
                x, y, 0,
                 x, y + height, 0,
                 x + width, y + height, 0,
                 x + width, y, 0,
        };

        for (int i = 0; i < VERTEXES; i++) {
            for(int j = 0; j < 3; j++) {
                mVertexBuffer.put(coords[i * 3 + j]);
            }
        }
        
        float[] terxCoords = {
                // X, Y, Z
        		((float)mX) / mTexture.getTextureWidth() , ((float)mY) /mTexture.getTextureHeight() ,
        		((float)mX) / mTexture.getTextureWidth(), ((float)mY + mHeight) /mTexture.getTextureHeight(),
        		((float)mX + mWidth) / mTexture.getTextureWidth(), ((float)mY + mHeight) /mTexture.getTextureHeight(),
        		((float)mX + mWidth) / mTexture.getTextureWidth(), ((float)mY) /mTexture.getTextureHeight(),
        };
        
        for (int i = 0; i < VERTEXES; i++) {
            for(int j = 0; j < 2; j++) {
                mTextureBuffer.put(terxCoords[i * 2 + j]);
            }
        }
  
        mVertexBuffer.position(0);
        mTextureBuffer.position(0);
	}
}
